package com.yangrd.airship.upms.infrastructure;

import com.yangrd.airship.common.UserInfo;
import com.yangrd.airship.common.UserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yangrd
 * @date 2021/11/26
 */
@RequiredArgsConstructor

@Primary
@Component
public class CacheUserInfoService implements UserInfoService {

    private final List<UserInfoService> delegates;

    private final static Map<Integer, Optional<UserInfo>> USER_ID_2_USER = new ConcurrentHashMap<>();

    @Override
    public Optional<UserInfo> loadUser(Integer userId) {
        return USER_ID_2_USER.computeIfAbsent(userId, k -> delegates.iterator().next().loadUser(userId));
    }
}
